package com.sm.honkon.ui.model

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import au.com.safie.user.app.util.CacheUtil
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.app.App
import com.sm.honkon.data.bean.HandlerEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.livedata.BooleanLiveData

class AddHandlerViewModel : BaseViewModel() {
    val dao = App.database.handleDao()
    val uid = CacheUtil.getHandleUid()
    var handle = MutableLiveData<HandlerEntity>(HandlerEntity(uid))
    val isMan = BooleanLiveData(true)
    val isEdit = BooleanObservableField(false)
    val medicalOfficials = arrayListOf("住院医师", "主治医师", "副主任医师", "主任医师", "其他")
    val status = arrayListOf("正常", "禁用")

    fun insert(callback: () -> Unit) {
        handle.value?.let {
            if (it.workId.isEmpty()) {
                ToastUtils.showShort("请输入工号")
                return@let
            }
            if (it.name.isEmpty()) {
                ToastUtils.showShort("请输入姓名")
                return@let
            }
            if (it.age.isEmpty()) {
                ToastUtils.showShort("请输入年龄")
                return@let
            }
            if (it.medical_official.isEmpty()) {
                ToastUtils.showShort("请选择医师职称")
                return@let
            }
            if (it.mobile.isEmpty()) {
                ToastUtils.showShort("请输入联系手机")
                return@let
            }
            if (it.password.isEmpty()) {
                ToastUtils.showShort("请输入密码")
                return@let
            }
            viewModelScope.launch(Dispatchers.Default) {
                if (isEdit.get().not()) {
                    dao.insert(it)
                    CacheUtil.setHandleUid(uid + 1)
                } else {
                    dao.update(it)
                }
                withContext(Dispatchers.Main) {
                    callback()
                }
            }
        }
    }

}